package com.zlzsy.app.base.helper

import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.os.Build

/**
 * Created by niantuo on 2017/9/23.
 * 动态权限申请的辅助类
 */

class PermissionHelper(val activity: Activity, val mView: IPermissionView) {

    fun requestPermission(requestCode: Int, permission: Array<String>) {
        if (Build.VERSION.SDK_INT < 23)
            return
        activity.requestPermissions(permission, requestCode)
    }


    fun check(permission: Array<String>): List<String> {
        return permission.filter { !check(it) }
    }

    fun check(permission: String): Boolean {
        return if (Build.VERSION.SDK_INT < 23) true else activity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
    }

    fun onRequestPermissionsResult(requestCode: Int,
                                   permissions: Array<String>,
                                   grantResults: IntArray) {

        val deniedList = check(permissions)

        if (deniedList.isEmpty()) {
            mView.granted(requestCode)
        } else {
            mView.denied(requestCode, deniedList)
        }
    }


    interface IPermissionView {

        fun granted(requestCode: Int)

        fun denied(requestCode: Int, permission: List<String>)


    }


    companion object {
        val CAMERA_PERMISSION = Manifest.permission.CAMERA
        val CALL_PERMISSION = Manifest.permission.CALL_PHONE
        val WRITE_PERMISSON = Manifest.permission.WRITE_EXTERNAL_STORAGE
        val READ_PERMISSION = Manifest.permission.READ_EXTERNAL_STORAGE
        val DEVICE_PERMISSION = Manifest.permission.READ_PHONE_STATE
        val LOCATION_PERMISSION = Manifest.permission.ACCESS_COARSE_LOCATION
    }


}
